﻿using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System;
using System.Text;
using UnityEngine.UI;
public class NetClient : MonoBehaviour
{
    Socket socket;
    SocketBuffer socketBuffer;
    byte[] byteData = new byte[1024];

    public Text uitext;
    // Use this for initialization
    void Start()
    {
        socketBuffer = new SocketBuffer(6, RecvMsgOver);
        Initial();
    }

    void RecvMsgOver(byte[] alldata)
    {
        //接受到的一个数据包;包头+包体


    }

    void Initial()
    {
        //服务器地址
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

        IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 18010);

        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //三次握手 
        socket.BeginConnect(ipEndPoint, new System.AsyncCallback(ConnectBack), socket);
    }

    void ConnectBack(IAsyncResult result)
    {
        socket.EndConnect(result);
        Debug.Log("connect success");

    }

    void RecvCallBack(IAsyncResult ar)
    {
        //
        int Length = socket.EndReceive(ar);
        string tmpStr = Encoding.Default.GetString(byteData, 0, Length);
        Debug.Log("client recv=" + tmpStr);

        uitext.text = tmpStr;
        //  socketBuffer.RecvByte(ar.)
    }

    public void BeginRecv()
    {
        socket.BeginReceive(byteData, 0, 1024, SocketFlags.None, RecvCallBack, this);
    }

    void SendCallBack(IAsyncResult ar)
    {
        int byteSend = socket.EndSend(ar);
        Debug.Log("byte send count==" + byteSend);
    }

    public void BeginSend(string tmpStr)
    {
        byte[] data = Encoding.Default.GetBytes(tmpStr);
        socket.BeginSend(data, 0, data.Length, SocketFlags.None, SendCallBack, this);
    }

    // Update is called once per frame
    void Update()
    {
        BeginRecv();
        if (Input.GetMouseButtonUp(0))
        {
            BeginSend("123456789");
        }

        BeginRecv();
    }
}
